﻿using System;
using System.Collections.Generic;
using Ext.Net;
using System.Linq;
using System.Xml.Linq;
using System.Web.Configuration;
using BG.Service;
using BG.Data;
using Kwan.Data;
using Kwan.Helper.Strings;
using System.Diagnostics;
using Kwan.Helper.Xmls;

namespace BG.Web.Admin
{
    public partial class Default1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                Dictionary<string, object> cacheModule = UserUtil.GetModule(UserUtil.GetCookieRole());
                if (cacheModule == null) Response.Redirect("~/extlogin.aspx");

                Page.Title = WebConfigurationManager.AppSettings["title"];
                btnLoginUser.Text = Page.User.Identity.Name;

                IList<TModule> list = (TModule.status > 0).List<TModule>();

                IList<TModule> CheckedModule = list.AsQueryable().Where(c => cacheModule.ContainsKey(c.NameEN.ToLower())).ToList();

                var Parent = list.AsQueryable().Where(a => CheckedModule.Any(b => b.Pid == a.EntityID)).ToList() as IList<TModule>;

                var query = from TModule t in Parent
                            select new
                            {
                                Title = t.NameCN,
                                Items = (from TModule tt in CheckedModule.Where(c => c.Pid == t.EntityID)
                                         select new
                                         {
                                             Title = tt.NameCN,
                                             Icon = "resources/images/" + tt.NameEN + ".png",
                                             Id = t.NameEN + "_" + tt.NameEN
                                         })
                            };

                
                //List<BtnRight> rightList = new List<BtnRight>()
                //{
                //    new BtnRight{ID="btnCheckIN", Icon="resources/images/Order.png", Title="发卡"},
                //    new BtnRight{ID="btnCheckIN", Icon="resources/images/Order.png", Title="结账"}
                //};
                //Store2.DataSource = rightList;
                //Store2.DataBind();


                this.Store1.DataSource = query;
                this.Store1.DataBind();

                //List<BtnRight> listRight = new List<BtnRight>(
                //    new BtnRight( {})
                //);

                //DoCreateMenu(null, document.Descendants("group"));

                CreatedModuleMemu(null, CheckedModule, Parent);

                list.Clear();
                CheckedModule.Clear();
                Parent.Clear();
                Store1.Dispose();
            }
        }

        protected void RefreshRoomDS(object sender, StoreRefreshDataEventArgs e)
        {
            var roomList = (TRoom.status == 1).List<VRoom>();
            var roomClass = roomList.Distinct(p => p.ClassName, StringComparer.CurrentCultureIgnoreCase).ToList<VRoom>();
            var queryRoom = from VRoom t in roomClass
                            select new
                            {
                                Title = t.ClassName,
                                Items = (from VRoom tt in roomList.Where(c => c.Cid == t.Cid)
                                         select new
                                         {
                                             Title = tt.RoomNO,
                                             Icon = "resources/images/shop-open.png",
                                             Id = "Room_" + tt.EntityID
                                         })
                            };

            roomStore.DataSource = queryRoom;
            roomStore.DataBind();
            winRooms.Show();
        }

        [DirectMethod(ShowMask = true, Msg = "加载中...", Timeout = 10000)]
        public void RoomClick(int roomID)
        {
            btnSaveCheckIN.Hidden = false;
            btnSaveCheckOut.Hidden = true;
            txtOtherPrice.Hidden = true;
            winCheckIN.Title = "登记入住";

            txtDeposit.ReadOnly = false;
            txtIsDisCount.ReadOnly = false;
            txtAddress.ReadOnly = false;
            txtCustomerName.ReadOnly = false;
            txtMemo.ReadOnly = false;
            txtDays.ReadOnly = false;

            Stopwatch sw = new Stopwatch(); sw.Start();
            TCard t = new TCard() { BuildNo = "1", CardNo = "1", EndDate = "201109091124", FloorNo = "1", Memo = "", Port = 1, RoomNo = "" };
            int readInfo;
            Card.ReadCard(t, out readInfo);
            //if (readInfo == 0)
            if (t != null)
            {
                //ExtHelper.GetNotification("系统提示", "读卡成功").Show();
                VRoom room = (TRoom.entityID == roomID).ListFirst<VRoom>();

                //房间没有限制押金，从默认配置取
                if (room.Deposit == 0)
                {
                    XmlHelper xmlHelper = new XmlHelper(Server.MapPath("~/Helper/site.xml"));
                    room.Deposit = Convert.ToInt32(xmlHelper.Read("/Root/Deposit", ""));
                }

                txtDays.Text = "1";
                txtDeposit.Text = room.Deposit.ToString();


                //房价处理
                TUser u = (TUser.userName == Page.User.Identity.Name).ListFirst<TUser>();
                int days = Convert.ToInt32(txtDays.Text);
                double price = room.Price > 0 ? room.Price : room.ClassPrice;
                double reserve = room.Reserve > 0 ? room.Reserve : room.ClassReserve;
                float discount = (float)u.Discount / 100;
                double finalPrice = (int)discount * price; //最终打折价格
                if (finalPrice < reserve)
                {
                    finalPrice = reserve;
                }

                txtDisCount.Text = finalPrice.ToString();
                txtPrice.Text = price.ToString();
                txtRoomID.Text = room.EntityID.ToString();
                lblRoomNO.Text = room.RoomNO + " - " + room.ClassName;
                txtFloorNo.Text = room.Floor;

                txtCardNo.Text = t.CardNo;
                txtBuildNo.Text = t.BuildNo;

                txtIsDisCount.Checked = false;
                txtTotalPrice.Text = (price * days).ToString();
                winCheckIN.Show();
                ExtHelper.GetNotification("系统提示", Card.ErrMessage(readInfo) + "<br>" + sw.ElapsedMilliseconds).Show();
            }
            else
            {
                ExtHelper.GetNotification("系统提示", Card.ErrMessage(readInfo) + "<br>" + sw.ElapsedMilliseconds).Show();
            }
        }

        [DirectMethod]
        public void SetFormChange(int roomID)
        {
            TUser u = (TUser.userName == Page.User.Identity.Name).ListFirst<TUser>();

            VRoom room = (TRoom.entityID == roomID).ListFirst<VRoom>();
            if (room == null)
            {
                ExtHelper.ErrorMsg("系统提示", "请不要尝试非法操作！", winCheckIN.ClientID);
                return;
            }
            //房间没有限制押金，从默认配置取
            if (room.Deposit == 0)
            {
                XmlHelper xmlHelper = new XmlHelper(Server.MapPath("~/Helper/site.xml"));
                room.Deposit = Convert.ToInt32(xmlHelper.Read("/Root/Deposit", ""));
            }
            txtDeposit.Text = room.Deposit.ToString();
            int days = Convert.ToInt32(txtDays.Text);
            double price = room.Price > 0 ? room.Price : room.ClassPrice;
            double reserve = room.Reserve > 0 ? room.Reserve : room.ClassReserve;
            float discount = (float)u.Discount / 100;
            double finalPrice = (int)discount * price; //最终打折价格
            if (finalPrice < reserve)
            {
                finalPrice = reserve;
            }

            txtTotalPrice.Text = txtIsDisCount.Checked ? (finalPrice * days).ToString() : (price * days).ToString();
        }

        protected void btnCheckOut_Click(object sender, DirectEventArgs e)
        {
            //退房结账
            btnSaveCheckIN.Hidden = true;
            btnSaveCheckOut.Hidden = false;
            winCheckIN.Title = "退房结账";
            TCard t = new TCard() { BuildNo = "1", CardNo = "1", EndDate = "201111041200", FloorNo = "1", Memo = "", Port = 1, RoomNo = "0503" };
            int readInfo;
            Card.ReadCard(t, out readInfo);
            //if (readInfo == 0)
            if (t != null)
            {
                VOrder tt = (VOrder.roomNO == t.RoomNo).ListFirst<VOrder>();
                TRoom room = (TRoom.roomNO == t.RoomNo).ListFirst<TRoom>();

                if (tt == null || room == null)
                {
                    ExtHelper.GetNotification("系统提示", "无此房间信息！请检查卡片或房间信息是否被删除！").Show();
                    return;
                }

                txtOtherPrice.Hidden = false;

                txtDeposit.ReadOnly = true;
                txtIsDisCount.ReadOnly = true;
                txtAddress.ReadOnly = true;
                txtCustomerName.ReadOnly = true;
                txtMemo.ReadOnly = true;
                txtDays.ReadOnly = true;
                txtIdentityNO.ReadOnly = true;

                txtRoomID.Text = room.EntityID.ToString();
                lblRoomNO.Text = tt.RoomNO + " 房";

                txtCardNo.Text = t.CardNo;
                txtBuildNo.Text = t.BuildNo;
                txtFloorNo.Text = t.FloorNo;

                DateTime endDate = DateTime.ParseExact(t.EndDate + "00", "yyyyMMddHHmmss", System.Globalization.CultureInfo.InvariantCulture);
                txtDays.Text = (DateTime.Now.Date - endDate.Date).Days.ToString(); 

                //txtIsDisCount.Checked = tt.IsDisCount;
                txtDeposit.Text = tt.Deposit.ToString();
                //txtTotalPrice.Text = tt.TotalPrice.ToString();
                winCheckIN.Show();
            }
            else
            {
                ExtHelper.GetNotification("系统提示", Card.ErrMessage(readInfo)).Show();
            }
        }

        protected void btnSaveCheckOut_Click(object sender, DirectEventArgs e)
        {
            TCard t = new TCard() { BuildNo = "1", CardNo = "1", EndDate = "201109091124", FloorNo = "1", Memo = "", Port = 1, RoomNo = "A503" };
            int writeInfo = Card.WriteCard(t);
            //if(writeInfo==0)
            using (IConnectinContext cc = DBContext.Context1)
            {
                (VOrder.roomNO == t.RoomNo).Edit<TOrder>(a => a.Status = 3);
                (TRoom.entityID == Convert.ToInt32(txtRoomID.Text)).Edit<TRoom>(a => a.Status = 1);

                roomStore.DataBind();
                winCheckIN.Hide();
            }
        }

        protected void btnSaveCheckIN_Click(object sender, DirectEventArgs e)
        {
            using (IConnectinContext cc = DBContext.Context1)
            {
                TOrder t = new TOrder();
                t.RoomID = Convert.ToInt32(txtRoomID.Text);
                t.Status = 2;
                t.CheckInDate = DateTime.Now;
                t.Days = Convert.ToInt32(txtDays.Text);
                t.Deposit = Convert.ToInt32(txtDeposit.Text);
                //t.Enable = true;
                //t.IsDisCount = txtIsDisCount.Checked;
                //t.TotalPrice = Convert.ToInt32(txtTotalPrice.Text);
                DBContext.Save(t);

                (TRoom.entityID == t.RoomID).Edit<TRoom>(a => a.Status = 2);

                roomStore.DataBind();
                winCheckIN.Hide();
                winRooms.Hide();
            }
        }

        protected void BtnEditPassword_Click(object sender, DirectEventArgs e)
        {
            if (Page.User.Identity.IsAuthenticated)
            {
                TUser tt = (TUser.userName == Page.User.Identity.Name).ListFirst<TUser>();
                this.txtUserID.Text = tt.EntityID.ToString();
                txtUserName.Text = tt.UserName;
                winPassword.Show();
            }
            else
            {
                ExtHelper.ErrorMsg("访问错误", "请重新登录！", this.btnEditPassword.ClientID);
            }
            
        }

        protected void SavePasswordWindow(object sender, DirectEventArgs e)
        {
            TUser tt = (TUser.userName == Page.User.Identity.Name).ListFirst<TUser>();
            if (MD5.Md5Decrypt(tt.Password) == this.txtOldPassword.Text)
            {
                tt.Password = MD5.Md5Encrypt(txtNewPassword.Text);
                DBContext.Save(tt);
                winPassword.Hide();
            }
            else
            {
                ExtHelper.ErrorMsg("验证错误", "旧密码错误！", this.winPassword.ClientID);
            }
        }

        protected void BtnLogout_Click(object sender, EventArgs e)
        {
            UserUtil.Logout();
            string returnUrl = Request.QueryString["returnUrl"];
            returnUrl = returnUrl != null ? returnUrl : "~/Ext/Default.aspx";
            Response.Redirect(returnUrl, true);
        }

        #region 创建Menu(XML)
        private void DoCreateMenu(MenuPanel mp, IEnumerable<XElement> Parent)
        {
            foreach (XElement x in Parent)
            {
                string id = x.Attribute("id").Value;
                string Title = x.Attribute("title").Value;
                if (mp == null)
                {
                    mp = CreateMenuPanel(id, Title);
                    ControlPanel.Items.Add(mp);
                    DoCreateMenu(mp, x.Elements("item"));
                    mp = null;
                }
                else
                {
                    string itemID = mp.ID.Replace("mp_", "") + "_" + id;
                    mp.Menu.Add(CreateMenuItem(itemID, Title, Title));
                    if (x != Parent.Last())
                    {
                        mp.Menu.Add(new MenuSeparator());
                    }
                }
            }
        }
        #endregion

        #region 创建Menu(DataBase)
        private void CreatedModuleMemu(MenuPanel mp, IList<TModule> checkedList, IList<TModule> Parent)
        {
            foreach (TModule t in Parent)
            {
                if (mp == null)
                {
                    mp = CreateMenuPanel(t.NameEN, t.NameCN);
                    ControlPanel.Items.Add(mp);
                    IList<TModule> Child = checkedList.Where(a => a.Pid == t.EntityID).ToList();
                    if (Child.Count > 0)
                    {
                        CreatedModuleMemu(mp, checkedList, Child);
                    }
                    mp = null;
                }
                else
                {
                    string itemID = mp.ID.Replace("mp_", "") + "_" + t.NameEN;
                    mp.Menu.Add(CreateMenuItem(itemID, t.NameCN, "Kwan-icon-" + t.NameEN));

                    //三级目录
                    IList<TModule> Child = checkedList.Where(a => a.Pid == t.EntityID).ToList();

                    if (Child.Count > 0)
                    {
                        MenuItem mt = mp.Menu.Items[mp.Menu.Items.Count - 1] as MenuItem;
                        Menu mu = new Menu();
                        for (int i = 0; i < Child.Count; ++i)
                        {
                            TModule ttt = Child[i];
                            MenuItem mi = CreateMenuItem(itemID + "_" + ttt.NameEN, ttt.NameCN, "Kwan-icon-" + ttt.NameEN);
                            mi.Listeners.Click.Handler = "Kwan.addTab({ tabPanel: #{TabPanel1}, id: 'tab_' + this.id, title: this.text, icon: this.iconCls});";
                            mu.Add(mi);
                        }
                        mt.Menu.Add(mu);
                    }
                    if (t != Parent.Last())
                    {
                        mp.Menu.Add(new MenuSeparator());
                    }
                }
            }
        }
        #endregion

        #region 创建MenuPanel
        /// <summary>
        /// 创建MenuPanel
        /// </summary>
        /// <param name="id"></param>
        /// <param name="text"></param>
        /// <returns></returns>
        private MenuPanel CreateMenuPanel(string id, string text)
        {
            MenuPanel m = new MenuPanel();
            m.ID = "mp_" + id; m.Title = text; m.Expand();
            m.Menu.Listeners.ItemClick.Handler = "Kwan.addTab({ tabPanel: #{TabPanel1}, id: 'tab_' + menuItem.id, title: menuItem.text, icon: menuItem.iconCls});";
            return m;
        }
        #endregion

        #region 创建MenuItem
        /// <summary>
        /// 创建MenuItem
        /// </summary>
        /// <param name="id"></param>
        /// <param name="text"></param>
        /// <returns></returns>
        private MenuItem CreateMenuItem(string id, string text,string iconcls)
        {
            return new MenuItem { ID = id, Text = text, IconCls = iconcls };
        }
        #endregion


    }
}